<template>
   <div class="mywallet" style="flex:1;">
     <scroller class="scroller" style="position:fixed;top:0;bottom:0px;left:0;right:0;">
        <wxc-minibar title="充值">
            <!-- <div class="header-con" slot="middle">          
                <text class="header-title">充值</text>
             </div>    -->
             <text slot="right" class="rechange-toptxt" @click="gorechargerecord()">充值记录</text>
        </wxc-minibar>
        <div class="i_e_list">
          <div class="recharge-wrap">
               <div class="account_balance">
              <text class="balance-title">当前余额(元)</text>
              <text class="balance-rmb">{{capitalAvailable | fixed}}</text>
            </div>
           <div class="title">
                <text class="title-txt">请选择支付金额</text>
            </div>
            <div class="choose_money">
              <div class="choose_money_item" v-for="(item,index) in moneyarr" :style="toggleclass(item,index)" :key="index"  @click="choosemoney(item,index)">
                  <text style="font-family: PingFangSC-Medium;font-size: 36px;" :style="toggleclass1(item,index)" >{{item}}</text>
                  <image  src="http://zhongcai-test.oss-cn-beijing.aliyuncs.com/hch5/recharge_checked.png" class="sanjiao" v-if="active==index"></image>
              </div>
            </div>
            <div class="recharge_money">
              <text class="rechange-iptitle">输入充值金额</text>
              <div class="form_fr">
                  <input  :style="telColor" type="number" class="input" v-model="money" @focus="focusmoney = true" @blur="focusmoney = false" placeholder="最低充值金额50.00元">
              </div>        
            </div>
          </div>
            <div class="paylist">
                    <div class="pay_detail" @click="qiehuancheck(item)" v-for="(item,index) in paymodellist" :key="index+1/17"  :style="checkDiabled(item)"  >
                      <div class="pay_detail_fl">
                          <image class="pay_icon" :src="item.src"></image>
                          <text style="font-family: PingFangSC-Medium;font-size: 32px;color: #333333;margin-left:32px;">{{item.title}}</text>
                      </div>
                      <div class="pay_detail_fr">
                          <div v-if="!item.checkflag" style="width:38px;height:38px;background-color:white;border-radius:20px;border-width:1px;border-color:rgba(0,0,0,0.1);"></div>
                          <image v-if="item.checkflag" style="width:38px;height:38px;" src="http://zhongcai-test.oss-cn-beijing.aliyuncs.com/hch5/recharge_checked.png"></image>
                      </div>
                    </div>
                </div>
            <div class="button" @click="confirmrecharge()">
              <text style="font-family: PingFangSC-Medium;font-size: 32px;color: #FFFFFF;">确认充值</text>
            </div>
              
        </div>
     </scroller>
     <loading-big v-if="loadingshow"></loading-big>
	<!-- <wxc-loadingsp :show="loadingshow" type="custom"  loading-text="加载中..." m-url="http://img.alicdn.com/tfs/TB1Ep_9NVXXXXb8XVXXXXXXXXXX-74-74.gif" m-width="200" m-height="200" m-backgroundcolor="#212021" m-textcolor="#ffffff"> </wxc-loadingsp> -->
		
	<wxc-mask :show="alertCode" width="320" height="80" mask-bg-color="#333" :has-overlay="false"> 
		<div class="tip"><text class="tip-font">{{ content }}</text></div>
	</wxc-mask>
</div>
</template>

<script>
const modal = weex.requireModule("modal");
const navigator = weex.requireModule("navigator");
let sxglobalEvent = weex.requireModule("globalEvent");
let storage = weex.requireModule('storage')
import WxcLoadingsp from "../../components/modules/loading";
import { WxcMask, WxcPopup, Utils } from "weex-ui";
import WxcMinibar from "@/components/modules/wxc-minibar/index.js"
import { yearMonthdate } from "@/utils";
import { getBaseUrl, serialize } from "@/utils/index.js";
import { postResponsesToken } from "@/api.js";
import loadingBig from "@/components/modules/loading-big";

let recharge = new BroadcastChannel('app')

export default {
	data() {
		return {
			focusmoney:false,
			loadingshow:false,
			alertCode: false,
			current: 1,
			baseURL:'',
			content:"",
			active: 0, //当前激活的tab
			moneyarr: [100, 200, 500, 1000],
			capitalAvailable:'',
			contentStyle:{},
			paymodel: {
				title:''
			},
			money:100,
			paymodellist: [
				{
					src:"http://zhongcai-test.oss-cn-beijing.aliyuncs.com/hch5/zhiicon.png",
					title: "支付宝支付",
					type:"alipay",
					checkflag: true,
					disabled: false
				},
				{
					src:"http://zhongcai-test.oss-cn-beijing.aliyuncs.com/hch5/weiicon.png",
					title: "微信支付",
					type:"wechat",
					checkflag: false,
					disabled: false
				},
				{
					src:"http://zhongcai-test.oss-cn-beijing.aliyuncs.com/hch5/yinicon.png",
					title: "快捷支付",
					type:'yop',
					checkflag: false,
					disabled: false
				}
			]
		}
	},

	components: {
		WxcMask,
		WxcMinibar,
		WxcPopup,
    WxcLoadingsp,
    loadingBig

	},

	created() {
		this.baseURL = getBaseUrl(weex.config.bundleUrl, true);

		this.getPersonalDetails()

		recharge.onmessage =  (event)=> {
            // 获取资金信息
            this.getPersonalDetails()
        }
	},

	mounted(){
		const tabPageHeight = Utils.env.getPageHeight()

		this.addListtenerPayInfo();
		
		this.contentStyle = {
			height: tabPageHeight + "px",
			width: "750px"
		}
	},
  filters:{
     fixed(value) {
            return String(value).indexOf('.') ? Number(value).toFixed(2) : value+'.00'
        }
  },
	destroyed(){
		sxglobalEvent.removeEventListener("payInfo");
	},
	methods: {

		 // 获取缓存
        getItem (name) {
            return new Promise((resolve, reject)=>{
                storage.getItem(name, event => {
                    if (event.result === "success") {
                        resolve(event.data);
                    } else {
                        reject("获取数据失败");
                    }
                })
            })
        },
   

        // 获取个人信息
        getPersonalDetails() {
            this.getItem('personalDetails').then( (value) => {
                // 昵称， 头像，总资金, 积分
                let { capitalAvailable } = JSON.parse(value)
                
                this.capitalAvailable = capitalAvailable || '0.00'

            })
		},
		
		roundFn(n, decimals = 0) {
            return Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`)
		},
		
		addListtenerPayInfo() {
		//三方支付 监听
			sxglobalEvent.addEventListener("payInfo", params => {

				let { resultStatus , thirdType, msg} = params

				// if( !!resultStatus && (resultStatus != "9000" || resultStatus != "0") ){
				// 	modal.toast({ message: msg })
				// 	return false;
				// }

				// 支付宝微信跳转
				this.payResult( ( thirdType === "alipay" &&  String(resultStatus) === "9000") || ( thirdType === "wechat" && String(resultStatus) === "0" ) )

				
			})
		},
		

		payResult(state) {
			!!state ? this.paySuccess() : this.payError()
		},
		
		paySuccess() {
			navigator.push({ 
				url:this.baseURL +"views/mywallet/recharge_success.js?money="+this.money,
				animated:"true"
			})
		},


		payError() {
			navigator.push({ 
				url:this.baseURL +"views/mywallet/recharge_fail.js",
				animated:"true"
			})
		},

		telColor() {
			return {
				borderBottomColor: !this.focusmoney ? "#CECECE" : "#E70D0D"
			}
		},

		gopayalipay(name) {
			//跳转到 支付宝支付，调用支付宝客户端
			weex.requireModule("eventLoginModule").payThird(name); //alipay:支付宝 wechat.微信，yop:易宝
		},

		//thirdPay   新接口  合并消费和充值
		async gopaythirdresult(obj) {
			//三方支付   alipay:支付宝 wechat.微信，yop:易宝
			this.loadingshow = true;

			let reqBody = {
				type: obj.typename,
				operation: "recharge",
				amount: obj.amount
			}

			let idata = await postResponsesToken('thirdpay/pay/pay', reqBody)
			
			if (idata && idata.msg === "success") {
        		let callBack = idata.data.callBack
				obj.typename === 'yop' ? this.linkYop(callBack) : this.gopayalipay(obj.typename + "&=@&" + callBack)
				this.loadingshow = false
			} else {
				modal.toast({ message: "发生错误，充值失败" });
				this.loadingshow = false
			}
		},
		
		//跳转第三方易宝
		
		linkYop(datacallback) {
			storage.setItem("webviewUrl", JSON.stringify(datacallback), event => {
				if (event.result === "success") {
					navigator.push({ 
						url:this.baseURL +"views/webview/yeepay_webview.js?money="+this.money,
						animated:"true"
					})
				} else {
					modal.toast({ message: "缓存跳转失败" });
				}
			})
		},


		
		checkDiabled(item) {
			return item.disabled === true && { opacity: "0.4" }
		},
		
		confirmrecharge(){

			if( this.alert(this.money < 50, '最低充值金额为50元') && this.alert(this.paymodel.title == '', '请选择支付方式') ) {

				this.gopaythirdresult({
					typename:this.paymodel.type,
					amount: this.money
				})
			}

		},
		
		// 选择支付类型
		qiehuancheck(item) {
      this.paymodel = item;
      this.paymodellist.forEach(function(item){
        item.checkflag=false;
      })
       item.checkflag=true;
		},
		
		// 弹窗
		alert(state, title) {
			if(!state) return true;

			this.alertCode = true
			this.content = title

			setTimeout(() => { this.alertCode = false }, 2000);

			return false
		},
		
	
		
		gorechargerecord() {
			let url = getBaseUrl(weex.config.bundleUrl, true);
			navigator.push({
				url: url + "views/mywallet/rechargelist.js",
				animated: "true"
			});
		},
		
		toggleclass(item, index) {
			if (index == this.active) {
				return {
					borderWidth: "3px",
					borderColor: "#E70D0D",
          borderStyle: "solid",
          backgroundColor:'#FFE4E3'
				};
			} else {
				return {
					borderWidth: "3px",
					borderColor: "#D1D1D1",
          borderStyle: "solid",
         
				};
			}
		},

		toggleclass1(item, index) {
			if (index == this.active) {
				return {
          color: "#E53935",
         
				};
			} else {
				return {
          color: "#333",
         
				};
			}
		},
		
		choosemoney(item, index) {
			this.active = index;
			this.money = item
		}
	}
};
</script>

<style scoped>
.rechange-toptxt{
  font-size: 30px;
  color:#333333;
}
.pay_icon{
  width:44px;
  height:44px;
}
.mywallet {
  position: relative;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #f5f5f5;
}
.wallet_info {
  width: 686px;
  height: 240px;
  margin-top: 24px;
  margin-left: 32px;
  margin-right: 32px;
  /* background-color: #FFFFFF; */
  display: flex;
  flex-direction: row;
}
.wallet_info_item {
  background-color: #ffffff;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 228px;
}
.wallet_info_item_md {
  position: relative;
}
.left_line {
  position: absolute;
  top: 120px;
  margin-top: -21px;
  left: 0;
  width: 2px;
  height: 43px;
  background-color: #d1d1d1;
}
.right_line {
  position: absolute;
  top: 120px;
  margin-top: -21px;
  right: 0;
  width: 2px;
  height: 43px;
  background-color: #d1d1d1;
}
.wallet_list_item {
  width: 750px;
  height: 112px;
  border-bottom-width: 2px;
  border-bottom-style: solid;
  border-bottom-color: #d8d8d8;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  background-color: #ffffff;
}
.wallet_list {
  margin-top: 24px;
}
.flex_lf {
  display: flex;
  flex-direction: row;
  margin-left: 32px;
  align-items: center;
}
.flex_rt {
  display: flex;
  flex-direction: row;
  margin-right: 32px;
}
.title {
  padding-left: 32px;
  padding-top: 24px;
  padding-bottom: 24px;
  background-color: #fff;
}
.choose_money {
  padding-left: 32px;
  padding-right: 32px;
  background-color: #ffffff;
  flex-direction: row;
  flex-wrap:wrap;
  justify-content: space-between;
}
.choose_money_item {
  
  border-radius: 4px;
  width: 330px;
  height: 140px;
  justify-content: center;
  align-items: center;
  margin-bottom:26px;
}
.recharge_money {
  height: 112px;
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-left:32px;
  margin-right:32px;
  border-bottom-width: 1px;
  border-bottom-style: solid;
  border-bottom-color: rgb(245, 245, 245);
  background-color: #f5f5f5;
  margin-bottom:26px;
}
.rechange-iptitle{
  color:#2B3940;
  padding-right:66px;
  padding-left:32px;
}
.account_balance {
  background-color: #ffffff;
  flex-direction:column;
  align-items: center;
 
}
.balance-rmb{
  font-size:70px;
  color:#2B3940;
  text-align: center;
  padding-top:10px;
}
.balance-title{
  color:#2B3940;
  font-size:24px;
  padding-top:40px;
  text-align: center;
}
.form_fr {
  width: 350px;
}
.sanjiao{
	position: absolute;
	top: 8px;
	right: 8px;
	width:38px;
	height:38px;
  }
.choosedpay {
  display: flex;
  justify-content: space-between;
  height: 112px;
  background-color: white;
  flex-direction: row;
  align-items: center;
}
.choosedpay_fl {
  align-items: center;
  margin-left: 32px;
  display: flex;
  flex-direction: row;
}
.choosedpay_fr {
  display: flex;
  flex-direction: row;
  margin-right: 32px;
  align-items: center;
}
.paylist{
  background-color: #fff;
}
.paylist_title {
  height: 112px;
  line-height: 112px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-bottom-width: 1px;
  border-bottom-style: solid;
  border-bottom-color: rgba(0, 0, 0, 0.1);
}
.title-txt{
  color:#676F73;
  font-size:28px;
}
.pay_detail {
  border-bottom-width: 1px;
  border-bottom-style: solid;
  border-bottom-color: rgba(0, 0, 0, 0.1);
  height: 96px;
  /* line-height: 96px; */
  align-items: center;
  display: flex;
  justify-content: space-between;
  flex-direction: row;
  margin-left:32px;
  margin-right:32px;
}
.pay_detail_fl {
  display: flex;
  flex-direction: row;
 
 
}
.pay_detail_fr {
 
}
.discover_item_arrow {
  font-family: iconfttf;
  font-size: 26px;
  color: #d8d8d8;
  margin-left: 19px;
}
.button{
    margin-top:40px;
    height: 96px;
    background-color: #E53935;
    display: flex;
    align-items: center;
    justify-content: center;
}

.tip-font {
  color: #fff;
  font-size: 28px;
  align-items: center;
  justify-content: center;
}

.tip {
  width: 320px;
  height: 80px;
  justify-content: center;
  align-items: center;
  display: flex;
}

.header-title {
  font-size: 34px;
  color: #fff;
  font-weight: 600;
  font-family: PingFangSC-Medium;
}

.input {
  height: 80px;
  background-color: transparent;
  color:#E53935;
  font-size:34px;
}
.recharge-wrap{
  background-color: #fff;
  margin-bottom:24px;
}
</style>
